package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName EmployeeRealm
 * Create by Mike
 * Date 2021/8/16 9:55
 */
public class EmployeeRealm extends AuthorizingRealm {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前访问员工
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        if (employee.isAdmin()){
            List<String> roles = roleService.listAll().stream()
                    .map(Role::getSn)
                    .collect(Collectors.toList());
            info.addRoles(roles);
            info.addStringPermission("*:*");
            return info;
        }

        //根据用户的id查询该用户拥有的角色编码
        List<String> roles = roleService.queryByEmployeeId(employee.getId()).stream()
                .map(Role::getSn)
                .collect(Collectors.toList());
        info.addRoles(roles);
        //根据用户的id查询该用户拥有的权限表达式
        List<String> permissions = permissionService.queryExpressionByEmployee(employee.getId());
        info.addStringPermissions(permissions);
        return info;
    }

    //提供认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        Employee employee =  employeeService.queryByUsername(username);
        if (employee == null) {
            return null;
        }
        //有这个员工
        return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                ByteSource.Util.bytes(employee.getSalt()),this.getName());
    }
}
